package com.tyut.homework.service.impl;

import com.tyut.homework.pojo.Student;
import com.tyut.homework.repository.StudentRepository;
import com.tyut.homework.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentRepository studentRepository;

    @Override
    public Student save(Student student) {
        Student save = studentRepository.save(student);
        return save;
    }

    @Override
    public int delete(Integer id) {
        Student student = new Student();
        student.setId(id);
        studentRepository.delete(student);
        return 0;
    }

    @Override
    public int update(Student student) {
        Student student1 = studentRepository.saveAndFlush(student);
        if (student1 != null){
            return 1;
        }else {
            return 0;
        }
    }

    @Override
    public Student find(Integer id) {
        return studentRepository.findStudentById(id);
    }

    @Override
    public List<Student> findAll() {
        return null;
    }

    @Override
    public Page<Student> getPage(Integer pageNum, Integer pageLimit) {
        Sort sort = new Sort(Sort.Direction.ASC,"id");
        Pageable pageable = new PageRequest(pageNum, pageLimit, sort);
        return studentRepository.findAll(pageable);
    }

    @Override
    public void deleteInbatch(String[] ids) {
        List<Student> list = new ArrayList<>();
        for (int i = 0; i< ids.length; i++){
            Student student = new Student();
            student.setId(Integer.valueOf(ids[i]));
            list.add(student);
        }
        studentRepository.deleteInBatch(list);
    }

    @Override
    public List<Student> findByLike(Integer type, String content) {
        if (type == 0){
            return studentRepository.findByIdLike(Integer.valueOf(content));
        }else if (type == 1){
            return studentRepository.findByNameLike(content);
        }else {
            return studentRepository.findByPhoneLike(content);
        }
    }

    @Override
    public int updateStatus(Integer id) {
        return studentRepository.updateStatus(id);
    }

    @Override
    public List<Student> getListNotMatch() {
        return studentRepository.getListNotMatch();
    }

    @Override
    public Student findInfoByClazz(String clazz) {
       return studentRepository.findInfoByClazz(clazz);
    }


}
